%%%-------------------------------------------------------------------
%%% File    : p6.erl
%%% Author  : Plamen Dragozov <plamen at dragozov.com>
%%% Description : 
%%% The sum of the squares of the first ten natural numbers is,
%%% 1^(2) + 2^(2) + ... + 10^(2) = 385
%%% The square of the sum of the first ten natural numbers is,
%%% (1 + 2 + ... + 10)^(2) = 55^(2) = 3025
%%% Hence the difference between the sum of the squares of the first 
%%% ten natural numbers and the square of the sum is 3025 − 385 = 2640.
%%%
%%% Find the difference between the sum of the squares of the first one 
%%% hundred natural numbers and the square of the sum.
%%%
%%% Created :  2 Dec 2008
%%%-------------------------------------------------------------------
-module(p6).

%% API
-export([solution/1]).

%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: solution(N) -> int()
%% Description:
%% Returns the result of 
%% sum([1**2, ..., N**2]) -  sum([1, ..., N])**2
%%--------------------------------------------------------------------

%(1+2+3+...+n)**2 - (1**2 + 2**2 + 3**2 + ... +n**2) =
% (1**2 + 2**2 + ... + n**2) 
% + 2*[n*((n-1) + ...+3+2+1) + (n-1)*(n-2+...+3+2+1) + ... + 3*(2+1) + 2*1]
% - (1**2 + 2**2 + ... + n**2) =
% 2*[N*(N-1 + ... 3+2+1) + (N-1)*(N-2+...+3+2+1) + ... + 3*(2+1) + 2*1]

solution(0) -> 0;
solution(N) when N > 0 ->
    2*sum(2, 1, N - 1, 0).

sum(_, _, 0, Acc) -> Acc;
sum(I, Sum, Counter, Acc) ->
    sum(I + 1, Sum + I, Counter - 1, Acc + I*Sum).
